package com.lqzs.businessmanager.service

import android.accessibilityservice.AccessibilityService
import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.EditText
import androidx.annotation.RequiresApi
import androidx.lifecycle.viewModelScope
import androidx.room.util.wrapMappedColumns
import com.lqzs.businessmanager.Config
import com.lqzs.businessmanager.Config.Companion.SCROLL_TIMER
import com.lqzs.businessmanager.Config.Companion.SCROLL_TIMER_SHORT
import com.lqzs.businessmanager.Config.Companion.merChantRecylerViewId
import com.lqzs.businessmanager.base.BaseViewModel
import com.lqzs.businessmanager.bean.MerChantInfo
import com.lqzs.businessmanager.bean.response.ReviewInfoResponse
import com.lqzs.businessmanager.dao.AccessDataBase
import com.lqzs.businessmanager.dao.MerChantDao
import com.lqzs.businessmanager.dao.ReplyDao
import com.lqzs.businessmanager.http.HttpUtils
import com.lqzs.businessmanager.http.RetrofitService
import com.lqzs.businessmanager.http.addMerChantInfo
import com.lqzs.businessmanager.http.makeRequest
import com.lqzs.businessmanager.utils.PreferencesUtil
import com.lqzs.businessmanager.utils.nodeOnClick
import com.lqzs.businessmanager.utils.scrollByNode
import com.lqzs.businessmanager.utils.setEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger

@Suppress("DEPRECATION")
class MerchantModel: BaseViewModel(){

    companion object{
        val TAG: String = MerchantModel::class.java.name
    }
    @SuppressLint("StaticFieldLeak")
    private lateinit var mService: AccessibilitySampleService
    private lateinit var merChantDao: MerChantDao
    private lateinit var replyDao: ReplyDao
    private lateinit var mRetrofitService: RetrofitService
    //是否打开评论页面 0未打开 1已打开
    val isClickDate = AtomicInteger(0)
    val isScrollChange = AtomicInteger(0)
    var editMerChantInfo:MerChantInfo? = null
    val isClickTab = AtomicInteger(0)
    //评价来源
    private val isClickSource = AtomicInteger(0)
    private var isClickRepay = AtomicBoolean(true) //是否有回复点击
    private var tabType = AtomicInteger(0)   //1 美团 2 大众点评
    @Volatile
    var dateType = 0   //评价时间 所有时间 1

    private val mutex = Mutex()
    private val mCurrentMapSet = ConcurrentHashMap<String,MerChantInfo>()

    private var isClickRefreshNoData = AtomicInteger(0) //如果页面加载不出来数据，刷新3次如果显示无数据

    @RequiresApi(Build.VERSION_CODES.O)
    fun init(service: AccessibilitySampleService){
        mService = service
        merChantDao = AccessDataBase.getDataBase().merChantDao()
        replyDao = AccessDataBase.getDataBase().replayDao()
        mRetrofitService = HttpUtils.getInstance().create()
        isClickDate.set(0)
        isScrollChange.set(0)
        isClickTab.set(0)
        isClickRepay.set(true)
        isClickSource.set(0)
        tabType.set(0)
        dateType = 0
        mCurrentMapSet.clear()
        isClickRefreshNoData.set(0) // 优化：将 isClickRefreshNoData 的初始化放在 init 函数中
    }

    /**
     * 美团开店宝所有事件处理
     */
    suspend fun handleMerChantModel(service: AccessibilitySampleService,rowNode: AccessibilityNodeInfo,event: AccessibilityEvent){
        mService = service
        //如果遇到弹窗则先关闭弹窗
        if (findId(rowNode,Config.closeDialogId)){
            return
        }

        if (!PreferencesUtil.getBoolean(mService, Config.Merchant_DaZhongDianPing,false)/* || !PreferencesUtil.getBoolean(mService, Config.Merchant_MT,false)*/){
            //打开顾客评价页面
            if (findTextClick(rowNode,"顾客评价")){
                isClickDate.set(0)
                return
            }
        }

        if (isClickTab.get() == 0){
            if (!PreferencesUtil.getBoolean(mService, Config.Merchant_DaZhongDianPing,false)){
                if (findTextClick(rowNode,"大众点评")){
                    isClickTab.set(1)
                    tabType.set(2)
                    isClickDate.set(0)
                    isClickRepay.set(true)
                    isClickSource.set(0)
                }
            }/*else if (!PreferencesUtil.getBoolean(mService, Config.Merchant_MT,false)){
                if (findTextClick(rowNode,"美团")){
                    isClickTab.set(1)
                    tabType.set(1)
                    isClickDate.set(0)
                    isClickRepay.set(true)
                    isClickSource.set(0)
                }
            }*/
        }

        if (findText(rowNode,"近30天")){
            if (findTextClick(rowNode,"全部") && findTextClick(rowNode,"确定")){
                rowNode.refresh()
                isClickDate.set(1)
            }
        }
        //选择时间
        if (isClickDate.get() == 0) {
            when(tabType.get()){
                1->{
                    if (!PreferencesUtil.getBoolean(mService, Config.Merchant_MT_All_Date,false)){
                        findTextClick(rowNode,"近30天")
                        if (findTextClick(rowNode,"全部") && findTextClick(rowNode,"确定")){
                            rowNode.refresh()
                        }
                        return
                    }
                }
                2->{
                    if (!PreferencesUtil.getBoolean(mService, Config.Merchant_DADP_All_Date,false)){
                        findTextClick(rowNode,"近30天")
                        if (findTextClick(rowNode,"全部") && findTextClick(rowNode,"确定")){
                            rowNode.refresh()
                        }
                        return
                    }
                }
                else->{
                    if (!PreferencesUtil.getBoolean(mService, Config.Merchant_MT_All_Date,false)||!PreferencesUtil.getBoolean(mService, Config.Merchant_DADP_All_Date,false)){
                        findTextClick(rowNode,"近30天")
                        if (findTextClick(rowNode,"全部") && findTextClick(rowNode,"确定")){
                            rowNode.refresh()
                        }
                        return
                    }
                }
            }
        }

        if (tabType.get()==2 && findText(rowNode,"回复成功")){
            isClickTab.set(0)
            isClickRepay.set(true)
            isClickSource.set(0)
            mService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
        }

        if (findText(rowNode,"团购评价") || findText(rowNode,"买单评价") || findText(rowNode,"其他评价")){
            if (findTextClick(rowNode,"全部")){
                rowNode.refresh()
            }
        }

        if (findText(rowNode,"未回复")){
            if (findTextClick(rowNode,"全部")){
                rowNode.refresh()
            }
        }




        if (isClickRepay.get()){
            if (findTextClick(rowNode,"未回复")||findTextClick(rowNode,"已回复")){
                rowNode.refresh()
                isClickRepay.set(false)
                findTextClick(rowNode,"全部")
                PreferencesUtil.putBoolean(mService,Config.Merchant_DZDP_NO_REPLAY,true)
                return
            }
        }
        if (isClickSource.get() == 0){
            if (findTextClick(rowNode,"团购评价")||findTextClick(rowNode,"买单评价")||findTextClick(rowNode,"其他评价")){
                rowNode.refresh()
                isClickSource.set(1)
                findTextClick(rowNode,"全部")
                PreferencesUtil.putBoolean(mService,Config.Merchant_DZDP_NO_REPLAY,true)
                return
            }
        }

        viewModelScope.launch(Dispatchers.IO) {
            if (findText(rowNode, "评价时间")){
                dateType = 1
            }
        }
        //查找列表节点
        findRecylerView(rowNode)


        if (isClickRefreshNoData.get()<3){
            if (findTextClick(rowNode,"暂无评价，请持续关注")){
                isClickRefreshNoData.set(isClickRefreshNoData.get()+1)
                return
            }
        }

    }

    /**
     * 查找列表数据分析
     */
    suspend fun findRecylerView(rowNode: AccessibilityNodeInfo) {
        val rvList  = rowNode.findAccessibilityNodeInfosByViewId(merChantRecylerViewId)
        if (rvList.isNullOrEmpty() || rvList.size<=0)
            return
        val mRvNodeInfo = rvList[0]?:return
        mutex.withLock {
            mRvNodeInfo.refresh()
            for(i in 0 until  mRvNodeInfo.childCount){
                val childNodeInfo = mRvNodeInfo.getChild(i) ?: continue
                //如果便利节点为空则跳出
                childNodeInfo.className ?:continue

                val replyNodeList = childNodeInfo.findAccessibilityNodeInfosByText("回复")
                val complaintNodeList = childNodeInfo.findAccessibilityNodeInfosByText("投诉")
                if (!replyNodeList.isNullOrEmpty() && !complaintNodeList.isNullOrEmpty()){
//                    viewModelScope.launch {
//                        handlerLog(childNodeInfo)
//                    }
                    val mMerChantInfo = MerChantInfo()
                    queryItem(childNodeInfo, mMerChantInfo, StringBuffer(), mRvNodeInfo, replyNodeList[replyNodeList.size-1].parent,i == mRvNodeInfo.childCount - 1)
                }else{
                    if (i==mRvNodeInfo.childCount-1&&mRvNodeInfo.isScrollable){
                        scrollRecylerView(childNodeInfo,mRvNodeInfo)
                    }
                }
            }
        }
    }

    //遍历节点Log日志
    private fun handlerLog(mRvNodeInfo: AccessibilityNodeInfo) {
        for(i in 0 until  mRvNodeInfo.childCount){
            val childNodeInfo = mRvNodeInfo.getChild(i) ?: continue
            //如果便利节点为空则跳出
            childNodeInfo.className ?:continue
            if (childNodeInfo.text!=null){
                Log.d(TAG, "handlerLog: ${childNodeInfo.className}      ${childNodeInfo.text}")
            }
            handlerLog(childNodeInfo)
        }
    }

    /**
     * 执行滑动事件
     */
    suspend fun scrollRecylerView(childNodeInfo: AccessibilityNodeInfo,rvNodeInfo: AccessibilityNodeInfo) {
        if (findText(rvNodeInfo,"依据平台规则，已折叠部分评价")) {
            delay(SCROLL_TIMER_SHORT)
            if (!PreferencesUtil.getBoolean(mService, Config.Merchant_DZDP_ZD,false)){
                findTextClick(rvNodeInfo,"依据平台规则，已折叠部分评价")
            }else{
                finishActivity()
            }
        }else{
            delay(SCROLL_TIMER_SHORT)
            if (!scrollByNode(mService,childNodeInfo,0,-200) && isScrollChange.get()<3){
                isScrollChange.set(isScrollChange.get()+1)
            }else if (isScrollChange.get()<6){
                scrollByNode(mService,rvNodeInfo,0,-200)
                isScrollChange.set(isScrollChange.get()+1)
            }else{
                PreferencesUtil.putBoolean(mService, Config.Merchant_DZDP_ZD,true)
                finishActivity()
            }
        }
    }
    private fun finishActivity(){
        isClickTab.set(0)
        mService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
        when(tabType.get()){
            1->{
                PreferencesUtil.putBoolean(mService, Config.Merchant_MT,true)
                if (dateType==1){
                    PreferencesUtil.putBoolean(mService,Config.Merchant_MT_All_Date,true)
                }
            }
            2->{
                PreferencesUtil.putBoolean(mService, Config.Merchant_DaZhongDianPing,true)
                if (dateType==1){
                    PreferencesUtil.putBoolean(mService,Config.Merchant_DADP_All_Date,true)
                }
            }
        }

        isScrollChange.set(0)
    }

    /**
     * 遍历整个条目
     */
    private suspend fun queryItem(
        itemNode: AccessibilityNodeInfo,
        merChantInfo: MerChantInfo,
        sbStr: StringBuffer,
        mRvNodeInfo: AccessibilityNodeInfo,
        replayNode: AccessibilityNodeInfo?,
        isLast: Boolean
    ) {
        if (itemNode.childCount == 1){
            val child = itemNode.getChild(0)?:return
            //如果便利节点为空则跳出
            child.className ?:return
            queryItem(child, merChantInfo, sbStr, mRvNodeInfo,replayNode,isLast)
        }else if (itemNode.childCount>1){
            for(i in 0 until  itemNode.childCount){
                val childNodeInfo = itemNode.getChild(i) ?: continue
                //如果便利节点为空则跳出
                childNodeInfo.className ?:continue
                val childText = childNodeInfo.text?.toString()


                if (!childText.isNullOrEmpty()) {
                    sbStr.append(childText)
                }
                if (tabType.get() == 2){
                    val kouweiList = itemNode.findAccessibilityNodeInfosByText("口味")
                    if (kouweiList.isNotEmpty()){
                        kouweiList[0]?.text?.toString()?.let {
                            if (it.contains("口味:")
                                &&it.contains("环境:")
                                &&it.contains("服务:")){
                                merChantInfo.fraction = it
                            }
                        }
                    }
                }


                if (findTextClick(childNodeInfo,"全文")){
                    childNodeInfo.refresh()
                }
                if (findContainsTextClick(childNodeInfo,"查看全部")){
                    childNodeInfo.refresh()
                }

                if (childText == "收起"||childText == "全文")
                    continue

                if (childText == merChantInfo.fraction)
                    continue
                if (childText?.isNotEmpty() == true){
                    when(i){
                        0->{
                            merChantInfo.userName = childText
                        }
                        1->{
                            merChantInfo.chaseCommentsTime = childText
                        }
                        else->{
                            if (merChantInfo.chaseComments.isNullOrEmpty()){
                                merChantInfo.chaseComments = childText
                            }else if (merChantInfo.orderDetails.isNullOrEmpty()){
                                merChantInfo.orderDetails = childText
                                merChantInfo.orderRecommend = childText
                            }
                        }
                    }
                }
                if (childNodeInfo.childCount>0){
                    queryViewGroup(childNodeInfo,merChantInfo,sbStr)
                }

                if (i == itemNode.childCount-1){
                    val strKey = sbStr.toString().replace("null", "").trim()
                    if (!mCurrentMapSet.containsKey(strKey)){
                        Log.i(TAG,"queryItem _____for :$merChantInfo")
                        merChantUpload(merChantInfo,strKey,replayNode)
                    }
                    if (isLast && mRvNodeInfo.isScrollable){
                        scrollRecylerView(childNodeInfo,mRvNodeInfo)
                    }
                }
            }
        }
    }

    //上传后台并且添加本地数据库
    private suspend fun merChantUpload(merChantInfo: MerChantInfo,sbKey: String,replayNode: AccessibilityNodeInfo?) {
        Log.i(TAG,"merChantUpload  :$merChantInfo   ${merChantInfo.merchantReplied.isNullOrEmpty()}")
        if (merChantInfo.merchantReplied.isNullOrEmpty()){
            //没有回复的数据直接进行请求
            makeRequest(addMerChantInfo(merChantInfo))
            val key = "${merChantInfo.userName}@${merChantInfo.chaseCommentsTime}"
            val replyInfo = replyDao.query(key)
            Log.d("LYF", "key1 $key reply ${replyInfo.toString()}")
            replyInfo?.let {
                merChantInfo.reviewId = replyInfo.reviewId
                merChantInfo.merchantReplied = merChantInfo.merchantReplied?.replace("商家：", "")
                if (merChantInfo.merchantReplied.isNullOrEmpty()) {
                    merChantInfo.upload = 4
                    merChantInfo.merchantReplied = replyInfo.replyContent
                } else{
                    merChantInfo.upload = 1
                }

            }
            Log.i("LYF","merChantUpload1  :${merChantInfo.upload}    $merChantInfo  ")
            if (merChantInfo.upload == 4 && replayNode?.isClickable == true) {
                //如果遇到未回复数据 则进行点击回复
                editMerChantInfo = merChantInfo
                nodeOnClick(replayNode)
                delay(5000)
            }
            mCurrentMapSet[sbKey] = merChantInfo
            merChantDao.insertOrUpdate(merChantInfo)
        }else{
            //回复数据查看本地数据库有没有  没有则直接上传
            merChantInfo.merchantReplied = merChantInfo.merchantReplied?.replace("商家：", "")
            //首先查询本地数据库中是否包含
            val merChantInfoList = merChantDao.findMerChantInfo(
                merChantInfo.userName,
                merChantInfo.fraction,
                merChantInfo.chaseComments,
                merChantInfo.orderDetails,
                merChantInfo.chaseCommentsTime,
                merChantInfo.reviewFollow
            )
            if (merChantInfoList.isNullOrEmpty()){
                makeRequest(addMerChantInfo(merChantInfo))
                val key = "${merChantInfo.userName}@${merChantInfo.chaseCommentsTime}"
                val replyInfo = replyDao.query(key)
                Log.d("LYF", "key $key reply ${replyInfo.toString()}")
                replyInfo?.let {
                    merChantInfo.reviewId = replyInfo.reviewId
                    merChantInfo.merchantReplied = merChantInfo.merchantReplied?.replace("商家：", "")
                    if (merChantInfo.merchantReplied.isNullOrEmpty()) {
                        merChantInfo.upload = 4
                        merChantInfo.merchantReplied = replyInfo.replyContent
                    } else{
                        merChantInfo.upload = 1
                    }
                }
                Log.i("LYF","merChantUpload  :${merChantInfo.upload}   $merChantInfo")
                if (merChantInfo.upload == 4 && replayNode?.isClickable == true){
                    //如果遇到未回复数据 则进行点击回复
                    editMerChantInfo = merChantInfo
                    nodeOnClick(replayNode)
                    delay(5000)
                }
                mCurrentMapSet[sbKey] = merChantInfo
                merChantDao.insertOrUpdate(merChantInfo)
            }else{
                merChantInfoList[0].let {info->
                    if (info.upload == 0){
                        makeRequest(addMerChantInfo(info))?.let {
                            merChantInfo.upload = 1
                            merChantInfo.reviewId = it.review_id
                            if (merChantInfo.merchantReplied.isNullOrEmpty()){
                                merChantInfo.merchantReplied = it.reply_content
                            }
                            merChantDao.insertOrUpdate(merChantInfo)
                        }
                    }
                }
            }

        }


    }

    /**
     * 遍历第三层级获取头像和评分内容
     */
    private suspend fun queryViewGroup(itemNode: AccessibilityNodeInfo, merChantInfo: MerChantInfo,sbStr: StringBuffer) {
        //评分 星级
        for(i in 0 until  itemNode.childCount){
            val childNodeInfo = itemNode.getChild(i) ?: continue
            //如果便利节点为空则跳出
            childNodeInfo.className ?:continue
            val childText = childNodeInfo.text?.toString()?.trim() ?: continue
            if (childText == "收起"||
                childText == "全文"||
                childText == "投诉"||
                childText == "回复"){
                continue
            }
            sbStr.append(childNodeInfo.text)
            if (childNodeInfo.text.contains("商家")){
                merChantInfo.merchantReplied = childText
            }else{
                merChantInfo.reviewFollow   +=  childText
                merChantInfo.reviewFollow   +=  "\n"
            }

            if (childNodeInfo.childCount>0){
                queryViewGroup(childNodeInfo,merChantInfo,sbStr)
            }
        }
    }

    /**
     * 根据字符串查找对应节点并进行点击
     */
    suspend fun findId(rowNode: AccessibilityNodeInfo,strDate :String) :Boolean{
        val mNodeList = rowNode.findAccessibilityNodeInfosByViewId(strDate)
        if (mNodeList.isNullOrEmpty())
            return false
        mNodeList.forEach {nodeInfo ->
            if (nodeInfo.isClickable){
                nodeOnClick(nodeInfo)
                nodeInfo.recycle()
                return true
            }else{
                nodeInfo.parent?.let {parent->
                    if (parent.isClickable){
                        nodeOnClick(parent)
                        parent.recycle()
                        return true
                    }
                }
            }
        }
        return  false
    }

    /**
     * 有没有对应的节点
     */
    suspend fun findText(rowNode: AccessibilityNodeInfo,strDate :String) :Boolean{
        val mNodeList = rowNode.findAccessibilityNodeInfosByText(strDate)
        return  !mNodeList.isNullOrEmpty()
    }

    /**
     * 根据字符串查找对应节点并进行点击
     */
    suspend fun findTextClick(rowNode: AccessibilityNodeInfo,strDate :String) :Boolean{
        val mNodeList = rowNode.findAccessibilityNodeInfosByText(strDate)

        if (mNodeList.isNullOrEmpty())
            return false

        mNodeList[0]?.let { nodeInfo ->
            nodeInfo.text?.toString()?.trim()?.let {
                if (it==strDate){
                    nodeInfo.parent?.let {parent->
                        if (parent.isClickable){
                            nodeOnClick(parent)
                            parent.refresh()
                            return true
                        }
                    }
                }
            }
        }
        return  false
    }


    /**
     * 包含数据
     */
    suspend fun findContainsTextClick(rowNode: AccessibilityNodeInfo,strDate :String) :Boolean{
        val mNodeList = rowNode.findAccessibilityNodeInfosByText(strDate)
        if (mNodeList.isNullOrEmpty())
            return false
        mNodeList[0]?.let { nodeInfo ->
            nodeInfo.text?.toString()?.trim()?.let {
                if (it.contains(strDate)&&it.contains("条回复")){
                    nodeInfo.parent?.let {parent->
                        if (parent.isClickable){
                            nodeOnClick(parent)
                            parent.refresh()
                            return true
                        }
                    }
                }
            }
        }
        return  false
    }

    /**
     * 事件处理
     */
    suspend fun handleEditText(mService: AccessibilitySampleService,rowNode: AccessibilityNodeInfo) {
        editMerChantInfo?.let {
            if (rowNode.childCount>0){
                for (i in 0 until rowNode.childCount){
                    val childNodeInfo = rowNode.getChild(i)?: continue
                    val childClassName = childNodeInfo.className?:continue
                    if (childClassName == EditText::class.java.name && i+1<rowNode.childCount){
                        val replyNode = rowNode.getChild(i+1)?: continue
                        replyNode.className?:continue
                        Log.d(TAG,"${it.chaseComments}    ${it.merchantReplied}")
                        if (setEditText(childNodeInfo,replyNode, it,mService)) {
                            it.upload = 1
                            merChantDao.update(it)
                        }
                    }else{
                        handleEditText(mService,childNodeInfo)
                    }
                }
            }
        }
    }
}